package com.android.aconportable;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class ChatHandler extends Activity {
	private Button btnRecord, btnStop, btnExit;
	private SeekBar skbVolume;
	private OutComePacket outcome;
	private InComePacket income;
	
	/*/////////Section of Battery////////////
	private TextView batteryInfo;
	private TextView timeInfo;
	private boolean start;
	private long startTime;
	private ArrayList<Integer> tempList;
	private ArrayList<Integer> voltageList;
	//*/////////battery End/////////////////
	
	UDPSocket socket;
	SIPEngineClient engine;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chathandler);
		setTitle("Recorder");
		
		AudioManager am  = (AudioManager) getSystemService(AUDIO_SERVICE);
		am.setMode(AudioManager.MODE_NORMAL);
		
		try {
			InetAddress inet = InetAddress.getByName("192.168.41.3");
			try {
				Socket tcpsocket = new Socket("192.168.41.3", 9800);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			socket = new UDPSocket(inet, 16403, 16404);
			socket.connect();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		init();
	}
	
	private void init(){
		//this.engine = AConPortableMain.engine;
		//this.socket = engine.getUdpSocket();
		outcome = new OutComePacket(socket);
		income = new InComePacket(socket);
		
		
		/*///////////Battery///////////
		start  = false;
		tempList = new ArrayList<Integer>();
		voltageList = new ArrayList<Integer>();
		//*////////////////////////////
		
		
		
		
		findView();
		VolumeSetup();
		setListener();
		income.play();
		
		/////////////////battery//////////////
		//setRegister();
		/////////////////////////////////////
		
	}

	private void findView(){
		btnRecord = (Button) this.findViewById(R.id.btnRecord);
		
		btnStop = (Button) this.findViewById(R.id.btnStop);
		
		btnExit = (Button) this.findViewById(R.id.btnExit);
		
		skbVolume = (SeekBar) this.findViewById(R.id.skbVolume);
		
		
		/*///////////////////battery//////////////////
		batteryInfo=(TextView)findViewById(R.id.textViewBatteryInfo);
        timeInfo=(TextView)findViewById(R.id.textViewTimeInfor);
        //*//////////////////////////////////////////
		
	}
	
	private void VolumeSetup(){
		skbVolume.setMax(100);
		skbVolume.setProgress(70);
		
		//audioTrack.setStereoVolume(0.7f, 0.7f);
		income.setVolumn(0.7f, 0.7f);
	}
	
	
	private void setListener(){
		btnRecord.setOnClickListener(new ClickEvent());
		btnStop.setOnClickListener(new ClickEvent());
		btnExit.setOnClickListener(new ClickEvent());
		skbVolume.setOnSeekBarChangeListener(volumeBar);
	}
	
	private SeekBar.OnSeekBarChangeListener volumeBar = new SeekBar.OnSeekBarChangeListener() {
		public void onStopTrackingTouch(SeekBar seekBar) {
			float vol = (float) (seekBar.getProgress())/ (float) (seekBar.getMax());
			income.setVolumn(vol, vol);
		}

		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
		}

		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			// TODO Auto-generated method stub
		}
	};
	
	
	/*@Override
	protected void onDestroy() {
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}*/

	class ClickEvent implements View.OnClickListener {
		public void onClick(View v) {
			if (v == btnRecord) {
				outcome.record();
			} else if (v == btnStop) {
				outcome.stop();
			} else if (v == btnExit) {
				outcome.stop();
				//outcome.finish();
				income.stop();
				//unregisterReceiver(batteryInfoReceiver);

				try {
					engine.leave();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				//unregisterReceiver(batteryInfoReceiver);
				finish();
			}
		}
	}
	
	
	/*//////////////////Battery Section//////////////////////
	private void setRegister(){
	    registerReceiver(batteryInfoReceiver,	new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}
	
	private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
 
			//int  health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
			//int  icon_small= intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,0);
			int  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
			//int  plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
			//boolean  present= intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
			//int  scale= intent.getIntExtra(BatteryManager.EXTRA_SCALE,0);
			//int  status= intent.getIntExtra(BatteryManager.EXTRA_STATUS,0);
			//String  technology= intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
			int  temperature= intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
			int  voltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
 
			/*batteryInfo.setText(
					"Health: "+health+"\n"+
					"Icon Small:"+icon_small+"\n"+
					"Level: "+level+"\n"+
					"Plugged: "+plugged+"\n"+
					"Present: "+present+"\n"+
					"Scale: "+scale+"\n"+
					"Status: "+status+"\n"+
					"Technology: "+technology+"\n"+
					"Temperature: "+temperature+"\n"+
					"Voltage: "+voltage+"\n");*/
	/*		batteryInfo.setText("level: " + level + "\n" +
					"temoerature: " + temperature + "\n" +
					"voltage: " + voltage + "\n" +
					"time: " + String.valueOf(System.currentTimeMillis()));
			
			if(level == 95 && start == false){
				start = true;
				startTime = System.currentTimeMillis();
				timeInfo.setText("Start Calculating...");
			}
			
			if(start){
				tempList.add(temperature);
				voltageList.add(voltage);
				if(level <= 45){
					int tempTemp = 0;
					int tempVolt = 0;
					
					for(int i = 0; i < tempList.size(); i++){
						tempTemp += tempList.get(i);
						tempVolt += voltageList.get(i);
					}
					
					timeInfo.setText("\nResult:\nDuration: " + (System.currentTimeMillis() - startTime) +
									"\nAverage Temperature: " + tempTemp / tempList.size() +
									"\nAverage Voltage: " + tempVolt / voltageList.size());
					start = false;
				}
			}
			//timeInfo.setText("Current time" + String.valueOf(System.currentTimeMillis()));
		}
	};*/
	
	
	
	
}
